package com.baixun.gassystem.mapper;
import com.baixun.gasentity.entity.SysDepartmentUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * SysDepartmentUser mapper层
 */

@Mapper
public interface SysDepartmentUserMapper extends BaseMapper<SysDepartmentUser> {

    @Select("SELECT p.permission " +
            "FROM sys_department_user u " +
            "JOIN sys_department_user_roles ur ON u.id = ur.user_id " +
            "JOIN sys_department_roles r ON ur.role_id = r.id " +
            "JOIN sys_department_role_permissions rp ON r.id = rp.role_id " +
            "JOIN sys_department_permissions p ON rp.permission_id = p.id " +
            "WHERE u.id = #{userId}")
    List<String> findPermissionsByUserId(@Param("userId") Long userId);


    // 获取用户所属的部门 ID
    @Select("SELECT department_id FROM sys_department_user WHERE user_id = #{userId}")
    Long getDepartmentIdByUserId(@Param("userId") Long userId);

    // 获取指定部门及其子部门的 ID
    @Select("<script>" +
            "WITH RECURSIVE sub_departments AS (" +
            "   SELECT id FROM departments WHERE id = #{departmentId} " +
            "   UNION ALL " +
            "   SELECT d.id FROM departments d " +
            "   INNER JOIN sub_departments sd ON d.parent_id = sd.id" +
            ") " +
            "SELECT id FROM sub_departments" +
            "</script>")
    List<Long> getSubDepartmentIds(@Param("departmentId") Long departmentId);

}